<?php 
/**
 * 订单模型
 * @author tangbl
 *
 */
class OrderModel extends Model {

	/**
	 array(
 		0.字段名
		1.验证规则 [require 字段必须、email 邮箱、url URL地址、currency 货币、number 数字]
		2.提示信息  {%usr_form_validata_email_email}
		3.验证条件 [0.(默认)存在字段就验证;1.必须验证;2.值不为空的时候验证]
		4.附加规则 [regex、function、callback、confirm、equal、in、length、between、
		         expire、ip_allow、ip_deny、unique]
		5.验证时   [1.新增数据时候验证;2.编辑数据时候验证;3.(默认)全部情况下验证]
	  );
	 */
	protected $_validate=array(
		
	);
	
	/**
	 * 定义自动完成
	 */
	protected $_auto = array(
		array('addtime', 'time', 1,'function')
	);
	
	/**
	 * 数据库表名
	 * protected $tableName = 'order';
	 */
	
	/**
	 * 
	 */
	public function getRoleOrder($cat){
		
		$time = $cat['time_view'];
		
		if($time==1){
			$begin = strtotime(date("Y-m-d"));
			$end   = strtotime(date("Y-m-d")." 23:59:59");
			$map['addtime'] = array(array("egt",$begin),array("elt",$end));
		}elseif($time==2){
			$arr = $this->getWeek();
			$map['addtime'] = array(array("egt",$arr['begin']),array("elt",$arr['end']));
		}elseif($time==3){
			$arr = $this->getMouth();
			$map['addtime'] = array(array("egt",$arr['begin']),array("elt",$arr['end']));
		}
		return $map;
	}
	
	/**
	 * 获取本月时间戳
	 */
	public function getMouth(){
	
		$begin = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
		$end   = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
	
		return array("begin"=>strtotime($begin),"end"=>strtotime($end));
	}
	
	/**
	 * 获取本周时间戳
	 */
	public function getWeek(){
		$year = date("Y");
		$month = date("m");
		$day = date('w');
		$nowMonthDay = date("t");
	
		$firstday = date('d') - $day;
		if(substr($firstday,0,1) == "-"){
			$firstMonth = $month - 1;
			$lastMonthDay = date("t",$firstMonth);
			$firstday = $lastMonthDay - substr($firstday,1);
			$time_1 = strtotime($year."-".$firstMonth."-".$firstday." 23:59:59");
		}else{
			$time_1 = strtotime($year."-".$month."-".$firstday." 23:59:59");
		}
			
		$lastday = date('d') + (7 - $day);
		if($lastday > $nowMonthDay){
			$lastday = $lastday - $nowMonthDay;
			$lastMonth = $month + 1;
			$time_2 = strtotime($year."-".$lastMonth."-".$lastday." 23:59:59");
		}else{
			$time_2 = strtotime($year."-".$month."-".$lastday." 23:59:59");
		}
	
		return array("begin"=>$time_1,"end"=>$time_2);
	}
	
	/**
	 * 根据对应的条件查找对应购物车的商品列表
	 * @param  array $map 条件数组
	 * @return array 节点列表数组
	 */
	public function listCart($map){
		
		$model = M("OrderCart");
		
		return $model->where($map)->select();
	}
	
	/**
	 * 分配订单到门店
	 */
	public function allotOutlet($map){
		
		$id   = $map['oldid'];
		$rows = $this->find($id);
		$flag = false;
		
		if($rows['id']){
			
			$outlet = $map['outlet'];
			$where  = array("id"=>$id);
			$data   = array("outletid"=>$outlet);
			$id     = $this->where($where)->save($data);
			$title  = $this->outletTitle($outlet,$rows['outletid']);
			
			$map['title']   = $title;
			$map['orderno'] = $rows["orderno"];
			$map['tableid'] = "Order";
			$map['dataid']  = $rows['id'];
			
			$flag = $this->addLog($map);
		}
		return $flag;
	}
	
	/**
	 * 分配订单到用户
	 * userid  旧用户id
	 * adminid 新用户id
	 */
	public function allotUser($map){
	
		$id   = $map['oldid'];
		$rows = $this->find($id);
		$flag = false;
		
		if($rows['id']){
			
			$module = M("OrderUser");
			$userid = $map['userid'];
			if($userid){
				$old  = array("oldid"=>$id,"adminid"=>$userid);
				$user = $module->where($old)->find();
			}
			
			$adminid = $map['adminid'];
			$new     = array("oldid"=>$id,"adminid"=>$adminid);
			$admin   = $module->where($new)->find();
			
			if($user['id']){
				
				$data = array("adminid"=>$adminid,"content"=>$map['content']);
				if($admin['id']){
					$data["id"] = $admin['id'];
				}else{
					$data["id"] = $user['id'];
				}
				$flag = $module->save($data);
			}else{
				
				if(empty($admin['id'])){
					$map['orderno'] = $rows["orderno"];
					$map['addtime'] = time();
					$flag = $module->add($map);
				}
			}
			
			if($flag){
				$map['title']   = $this->userTitle($adminid, $userid);
				$map['orderno'] = $rows["orderno"];
				$map['tableid'] = "Order";
				$map['dataid']  = $rows['id'];
				$this->addLog($map);
			}
		}
	
		return $flag;
	}
	
	/**
	 * 添加订单操作记录
	 */
	public function addLog($data){
		
		$data['addtime'] = time();
		return M("OrderOpreate")->add($data);
	}
	
	/**
	 * 生成分配到门店操作标题
	 */
	public function outletTitle($newid, $oldid=0){
		
		$titile  = "订单分配到门店:";
		$module  = M("Outlet");
		$titile .= $module->where("id=".$newid)->getField("title");
		if($oldid){
			$titile .= ",从门店:";
			$titile .= $module->where("id=".$oldid)->getField("title");
		}
		return $titile;
	}
	
	/**
	 * 生成分配到用户操作标题
	 */
	public function userTitle($newid, $oldid=0){
	
		$titile = "";
		$module = M("Admin");
		$user   = $module->find($newid);
		if($user['id']){
			$titile .= "订单分配到用户:";
			$titile .= $user['realname'].",编号:[".$user['id']."]";
			
			/* if($oldid){
				$user = $module->find($newid);
				$titile .= $user['realname'].",编号:[".$user['id']."]";
				$titile .= $user['realname'].",编号:[".$user['id']."]";
			} */
		}
		return $titile;
	}
	
	/**
	 * 处理套餐
	 */
	public function dealOrderPackage($cart){
		
		$m['company']  = $cart['company'];
		$m['outletid'] = $cart['outletid'];
		$m['tableid']  = $cart['tableid'];
		$m['dataid']   = $cart['dataid'];
		$m['addid']    = $cart['addid'];
		$m['addno']    = $cart['addno'];
		$m['orderno']  = $cart['orderno'];
		$m['id']       = $cart['id'];
			
		$map['packid'] = $cart['pid'];
		$field = "packid,size,unit,amount,title,typeid,pid,pno"; 
		$list  = D("ProductPackageView")->where($map)->field($field)->select();
		
		foreach($list as $v){
			
			$v = array_merge($v,$m);
			
			$typeid = $v['typeid'];
			if($typeid == 3){
				$this->dealOrderNumber($v);
			}elseif($typeid == 4){
				$this->dealOrderTime($v);
			}
		}
	}
	
	/**
	 * 处理计次
	 */
	public function dealOrderNumber($cart){
	
		$size   = intval($cart["size"]);
		$amount = intval($cart["amount"]);
		if($size){
			$amount = $amount*$size;
		}
		
		$cart['amount']  = $amount;
		$cart['remain']  = $amount;
		$cart['detailid']= $cart["id"];
		$cart['pid']     = $cart["pid"];
		$cart['isdel']   = 2;
		$cart['addtime'] = time();
		unset($cart["id"]);
		
		return M("OrderNumber")->add($cart);
	}
	
	/**
	 * 处理计时
	 */
	public function dealOrderTime($cart,$row=array()){
		
		$size   = intval($cart["size"]);
		$amount = intval($cart["amount"]);
		if($size){
			$amount = $amount*$size;
		}
		
		$cart['amount']  = $amount;
		$cart['remain']  = $amount;
		$cart['detailid']= $cart["id"];
		$cart['pid']     = $cart["pid"];
		$cart['isdel']   = 2;
		$cart['pay']     = 2;
		$cart['addtime'] = time();
		unset($cart["id"]);
		
		if($row){
			$cart = array_merge($cart,$row);
		}
		return M("OrderTime")->add($cart);
	}
	
	/**
	 * 秒转成小时
	 */
	public function calcTimeToHour($miao){
		
		$hour = 60*60;
		$hh   = floor($miao/$hour);
		$yu   = $miao%$hour;
		
		$mh   = number_format(($yu/$hour),1);
		if($mh<0.1){
			$mh = 0 ;
		}elseif($mh>0.1 && $mh<0.5){
			$mh = 0.5 ;
		}else{
			$mh = 1;
		}
		return $hh+$mh;
	}
	
	/**
	 * 计算计时产品的价格
	 */
	public function calcProductTime($pid, $num){
		
		$rows = M("Product")->find($pid);
		$cfgs = json_decode($rows["attr"],true);
		$hour = $this->calcTimeToHour($num);
		
		if(is_array($cfgs)){
			
			$price = $this->calcPrice($cfgs, $hour);
		}else{
			$price = doubleval($rows['sprice'])*$hour;
		}
		return $price;
	}
	
	/**
	 * 计算价格
	 */
	public function calcPrice($cfgs ,$hour){
		
		$keys = array_keys($cfgs);
		$max  = max($keys);
		$min  = min($keys);
		
		if($max>$hour){
			
			foreach($cfgs as $k=>$v){
				if($hour>$k){
					$max = $k;
				}
			}
			$h = $hour-$max;
			if($h<0){
				$h = 0;
			}
		}
		
		$maxp = doubleval($cfgs[$max]['sprice']);
		$minp = doubleval($cfgs[$min]['sprice'])*$h;
		return $maxp+$minp;
	}
	
	/**
	 * 更改订单价格
	 * @param $rows   array  计时数组
	 * @param $preice double 价格
	 */
	public function calcOrderTime($rows, $price){
		
		$map['company'] = $rows['company'];
		$map['orderno'] = $rows['orderno'];
		
		$data['totalfee'] = $price;
		$data['orderfee'] = $price;
		
		$id1 = M("Order")->where($map)->save($data);
		$id2 = M("OrderPay")->where($map)->save($data);
		return $id1+$id2;
	}
}